<template>
	<!-- 新增账本页面 -->
	<view id='add_book_container'>
		<uni-forms :modelValue="formData" label-position="left" label-width="50">
			<uni-forms-item label="账本名称:" name="name">
				<uni-easyinput type="text" v-model="formData.name" placeholder="请输入账本名称" />
			</uni-forms-item>
			<uni-forms-item label="账本类型:" name="type">
				<uni-easyinput disabled type="text" v-model="formData.type" placeholder="请输入账本类型" />
			</uni-forms-item>
			<uni-forms-item label="货币类型:" name="currency">
				<uni-easyinput disabled type="text" v-model="formData.currency" placeholder="请输入货币类型" />
			</uni-forms-item>
			<uni-forms-item label="是否默认:" name="isDf">
				<uni-easyinput disabled type="text" v-model="formData.isDf" placeholder="请输入账本类型" />
			</uni-forms-item>
		</uni-forms>
		<!-- 保存按钮 -->
		<view class="confirm_btn">
			<button
				type="default" 
				style="background-color: #efa31f; color: #fff;"
				@click="addBookHandle"
				>
				保存
			</button>
		</view>
	</view>
</template>


<script setup>
import {ref, onMounted} from 'vue'

// 表单数据
let formData = ref({
	name: "",
	type: "普通",
	currency:"CNY",
	isDf:"否"
})

async function addBookHandle(){
	if(formData.value.name == ""){
		uni.$showT("名称不能为空");
		return 0;
	}
	
	// 取出用户ID
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	const res = await uni.$http.post(`/accountBooks/addBook/${userInfo.id}/${formData.value.name}`);
	
	if(res.data.code == 0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
	afterHandle();
	uni.$showT("新增成功，即将跳转...");
	
	setTimeout(()=>{
		uni.navigateBack();
	}, 1500)
}

// 后置处理器
async function afterHandle() {
	// 删除成功后刷新数据
	let userInfo = JSON.parse(uni.getStorageSync('userInfo'));
	const res = await uni.$http.get(`/accountBooks/getAllByOpenId?openId=${userInfo.openid}`);
	// TODO通过默认账本字段排序
	uni.setStorageSync('accountBookData', res.data.data);
}
</script> 


<style lang ='scss' scoped>
#add_book_container{
	padding-top: 10px;
	width: 97vw;
	margin: 0 auto;
}

</style>